<template>
  <div class="cooperate-box">
    <vab-card shadow="always">
      <div class="flex_sb_wrap">
        <div class="flex">
          <div class="leve_title">
            需求提报
            <span v-if="searchForm">
              {{ searchForm.order_no ? `-${searchForm.order_no}` : '' }}
            </span>
          </div>
          <span class="default_text">
            创建人：
            <span v-if="searchForm">
              {{ searchForm.create_user_name || '' }}
            </span>
          </span>
          <span class="default_text">
            创建时间：
            <span v-if="searchForm">
              {{
                searchForm.create_at || dayjs().format('YYYY-MM-DD HH:ss:mm')
              }}
            </span>
          </span>
          <span class="default_text">状态：{{ _LeveTitle }}</span>
        </div>
        <div class="flex_end">
          <el-button
            size="small"
            v-if="_IsSave"
            class="button_update"
            @click="submitForm('0')"
          >
            暂存
          </el-button>
          <el-button size="small" type="primary" @click="submitForm('1')">
            提交
          </el-button>
          <el-button size="small" @click="handleClick('close')">取消</el-button>
        </div>
      </div>
    </vab-card>
    <div v-loading="loading">
      <!-- 采购基础信息 -->
      <BaseInfo
        :ref="(el: any) => (baseInfoRef = el)"
        :from_type="from_type"
        @switchBuyer="switchBuyer"
      />
      <!-- 采购产品信息 -->
      <TableMode :ref="(el: any) => (tableModeref = el)" :isWarn="isWarn" />
      <!-- 信用额度校验 -->
      <CreditDialog :ref="(el: any) => (creditDialogRef = el)" />
    </div>
  </div>
</template>
<script lang="ts" setup>
  defineOptions({
    name: 'Cooperate',
  })
  /**
   * @import
   */
  import { dayjs } from 'element-plus'
  import { getCustomerCategoryList } from '~/src/api/dms/home/homeCustomer'

  import TableMode from './components/TableMode.vue'
  import BaseInfo from './components/BaseInfo.vue'
  import CreditDialog from './components/CreditDialog.vue'

  import {
    customerOrderInfo,
    customerOrderInsert,
    customerOrderUpdate,
  } from '~/src/api/dms/customerOrder'
  import { ArrayFlat, CloseNowTabs } from '~/src/utils/utils'

  /**
   * @var
   */

  // 全局吐司
  const proxy: any = getCurrentInstance()?.proxy
  const route = useRoute()
  const router = useRouter()
  const { order_no, from_type } = route.query

  const tableModeref = ref()
  const baseInfoRef = ref()
  const creditDialogRef = ref()
  // 校验警告
  const isWarn = ref(false)
  const loading = ref(false)

  let searchForm = ref<any>({})

  /**
   * @method
   */

  // 地址自动识别
  const handleClick = (key: string) => {
    // 暂存
    if (key == 'update') {
      proxy.$Message('暂存成功', 'success')
      router.go(-1)
    }
    // 取消
    if (key == 'close') {
      router.go(-1)
    }
  }
  // 切换买方
  const switchBuyer = (value: string, lay = false) => {
    tableModeref.value.clearProduct(value, lay)
  }

  // 提交
  const submitForm = async (status = '1') => {
    // 基础信息校验

    if (status == '1') {
      const baseValidate = await baseInfoRef.value.baseFormRef.validate(
        (valid: any) => {
          if (valid) return true
          return false
        }
      )
      if (!baseValidate) return
    } else {
      const { buyer_customer_id } = baseInfoRef.value.baseForm
      if (!buyer_customer_id) {
        proxy.$Message('买方不能为空!', 'warning')
        return
      }
    }

    const productList = tableModeref.value.productList || []
    let _productList: any[] = []

    isWarn.value = false

    // 判空
    let VoidJudgment = false
    let VoidNumber = false

    if (productList.length && status == '1') {
      // 判空
      VoidJudgment = productList.some((item: any) => {
        return (
          !item.number ||
          !item.name ||
          item.buy_number == null ||
          item.buy_number.toString() == ''
        )
      })

      VoidNumber = productList.every((item: any) => {
        return Number(item.buy_number) > 0
      })

      if (VoidJudgment) {
        proxy.$Message('请正确填写采购产品信息!', 'warning')
        isWarn.value = true
        return
      }

      if (!VoidNumber) {
        proxy.$Message('采购数量必须大于0!', 'warning')
        isWarn.value = true
        return
      }
    }

    // 降维
    const mixArray = ArrayFlat(productList, 'children')
    // 取正品级[父级]
    const fatherArray = mixArray.filter(
      (item: any) => item.goods_type != '赠品'
    )
    // 取赠品级[儿子级]
    const sonArray = mixArray.filter((item: any) => item.goods_type == '赠品')
    // 同级传
    _productList = [
      ...fatherArray.map((item: any, i: number) => {
        return {
          brand: item.assistant_name, //品牌
          product_barcode: item.barcode, //产品条码
          product_code: item.number, // 产品编码
          product_name: item.name, //产品名称
          specification: item.specification, //规格
          number: item.buy_number, //采购数量
          remark: item.remark, //备注
          goods_type: item.goods_type, //产品类型
          serial_number: `${i + 1}`,
        }
      }),
      ...sonArray.map((item: any) => {
        return {
          brand: item.assistant_name, //品牌
          product_barcode: item.barcode, //产品条码
          product_code: item.number, // 产品编码
          product_name: item.name, //产品名称
          specification: item.specification, //规格
          number: item.buy_number, //采购数量
          goods_type: item.goods_type, //产品类型
          serial_number: item.serial_number,
        }
      }),
    ]

    const { baseForm } = baseInfoRef.value
    const shipping_address = baseForm?.shipping_address || []

    let data: any = {
      status, // 0草稿，-1删除，1正常
      buyer_customer_id: baseForm.buyer_customer_id || '',
      buyer_customer_name: '',
      invoice_type: baseForm.invoice_type,
      invoice_str: baseForm.invoice_str,
      tax_number: baseForm.tax_number || '',
      transport_type: baseForm.transport_type || '',
      pay_type: baseForm.pay_type || '',
      shipping_contact: baseForm.shipping_contact || '',
      shipping_tel: baseForm.shipping_tel || '',
      shipping_address: baseForm.shipping_address || [],
      address: baseForm.address,
      shipping_province: shipping_address ? shipping_address[0] : '',
      shipping_city: shipping_address ? shipping_address[1] : '',
      shipping_district: shipping_address ? shipping_address[2] : '',
      productList: _productList,
    }

    // 更新
    if (baseForm.order_no) {
      data.status = status
      data.order_no = baseForm.order_no
      customerOrderUpdate({ ...data }).then(async (res: any) => {
        const { credit_enough } = res.data
        // 关闭页签
        CloseNowTabs(route.path, route, router)

        // 暂存
        if (status == '0') {
          proxy.$Message('暂存成功！', 'success')
          router.go(-1)
          return
        }
        // 提交
        creditDialogRef.value.open(credit_enough)
      })
    } else {
      // 创建
      customerOrderInsert({ ...data }).then(async (res: any) => {
        const { credit_enough } = res.data
        // 关闭页签
        CloseNowTabs(route.path, route, router)

        // 暂存
        if (status == '0') {
          proxy.$Message('暂存成功！', 'success')
          router.go(-1)
          return
        }
        // 提交
        creditDialogRef.value.open(credit_enough)
      })
    }
  }

  // 获取复制信息
  const _GetCopyInfo = async () => {
    loading.value = true

    const res = await customerOrderInfo({ order_no })

    // 买方
    let cateRes = await getCustomerCategoryList()
    let row: any = null

    cateRes.data.forEach((item: any) => {
      if (item.uid == res.data.buyer_customer_id) row = item
    })

    if (from_type == 'copy') {
      res.data.order_no = ''
      res.data.create_user_name = ''
      res.data.create_at = ''
    }
    searchForm.value = res.data

    if (baseInfoRef.value) baseInfoRef.value.getUpdateData(res.data)
    if (tableModeref.value) {
      tableModeref.value.getUpdateData(res.data)
      tableModeref.value.clearProduct(row.number)
    }

    setTimeout(() => {
      loading.value = false
    }, 1000)
  }

  /**
   * @实例
   */
  // 标题显示
  const _LeveTitle = computed(() => {
    if (from_type == 'create') return '创建中'
    if (from_type == 'toHandle') return '处理中'
    if (from_type == 'copy') return '创建中'
  })
  // 暂存
  const _IsSave = computed(() => {
    // if (from_type == 'toHandle') return false
    return true
  })

  onMounted(() => {
    if (order_no) _GetCopyInfo()
  })
</script>
<style lang="scss" scoped>
  .marb-20 {
    display: inline-block;
    margin-bottom: 20px;
  }
  .border {
    width: 100%;
    border: 1px solid rgba(192, 196, 204, 0.6);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    border-radius: 5px;
    transition: var(--el-transition-box-shadow);
    transform: translate3d(0, 0, 0);
    padding: 4px;
    &:hover {
      border: 1px solid rgba(192, 196, 204, 0.8);
    }
    :deep() {
      .el-input__wrapper {
        box-shadow: none;
      }
      .el-input__wrapper:hover {
        box-shadow: none;
      }
    }
  }

  .searchfor {
    :deep() {
      .el-form-item {
        margin-bottom: 16px;
      }
    }
  }
</style>
